﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace ZFBActivation.Core
{
	public class PostDic : System.IDisposable
	{
		private Dictionary<string, string> _Dic = new Dictionary<string, string>();

		public PostDic() {
		}

		public PostDic(string data) {
			var keyvalue = data.Split('&', System.StringSplitOptions.RemoveEmptyEntries);
			foreach (var item in keyvalue) {
				var key = item.Substring(0, item.IndexOf('='));

				Set(key, item.Replace(key + "=", ""));
			}
		}
		public KeyValuePair<string, string>[] GetDic() {
			return _Dic.ToArray();
		}
		public string Get(string key) {
			if (_Dic.TryGetValue(key, out var value)) {
				return value;
			}
			return string.Empty;
		}

		public void Set(string key, object value) {
			if (_Dic.ContainsKey(key)) {
				_Dic[key] = value == null ? "" : value.ToString();
			} else {
				_Dic.Add(key, value == null ? "" : value.ToString());
			}
		}

		public string Build() {
			var sb = new StringBuilder();
			foreach (var item in _Dic) {
				sb.AppendFormat("{0}={1}&", HttpUtility.UrlEncode(item.Key), HttpUtility.UrlEncode(item.Value));
			}
			return sb.Length > 0 ? sb.Remove(sb.Length - 1, 1).ToString() : _Dic.Count.ToString();
		}

		public string GetBuild() {
			var sb = new StringBuilder();
			foreach (var item in _Dic) {
				sb.AppendFormat("{0}={1}&", item.Key, item.Value);
			}
			return sb.Length > 0 ? sb.Remove(sb.Length - 1, 1).ToString() : _Dic.Count.ToString();
		}

		public byte[] GetBytes() {
			return Encoding.UTF8.GetBytes(Build());
		}

		public bool Del(string key) {
			if (_Dic.ContainsKey(key)) return _Dic.Remove(key);
			return false;
		}

		public void Clear() {
			_Dic.Clear();
		}

		public void Dispose() {
			if (_Dic != null) {
				_Dic.Clear();
				_Dic = null;
			}
		}
	}
}